<?php
use app\common\service\QlRedis;
use think\facade\Db;
use think\facade\Request;
// 应用公共文件
function limitResult($field='', $userid = 0, $limit=5)
{
    $redis = new QlRedis();
    if ($redis->ttl($field.'_'.$userid) === -1) {
        $redis->del($field.'_'.$userid);
    }
    if ($redis->exists($field.'_'.$userid)) {
        $errcount = $redis->get($field.'_'.$userid);
        if ($errcount >= $limit) {
            return ['code'=>-1,'data'=>'','msg'=>'您输入密码错误次数过多或验证失败次数过多，已被临时冻结，请于2小时后重试'];
        } else {
            $redis->incr($field.'_'.$userid);
            return ['code'=>200,'data'=>'','msg'=>'本次请求失败'];
        }
    } else {
        $redis->set($field.'_'.$userid, 1, 7200);
        return ['code'=>200,'data'=>'','msg'=>'本次请求失败'];
    }
}
function allowCORS()
{
    header("Access-Control-Allow-Origin: *");
    header("Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE");
    header('Access-Control-Allow-Headers:Access-Token, access-token, Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With');
    header('Access-Control-Allow-Credentials: true');
    header("Content-type:application/json;chartset=uft-8");
    if (Request::isOptions()) {
        echo 'success';
        exit;
    }
}
function addoplog($data = [])
{
    if (!empty($data)) {
        if (!isset($data['is_admin']) || empty($data['is_admin'])) {
            $data['is_admin'] = 0;
        }
        if (!isset($data['opstatus']) || empty($data['opstatus'])) {
            $data['opstatus'] = 0;
        }
        $data['time'] = time();
        $data['_id'] = 'OL'.$data['time'].random_int(10000000, 99999999);
        $data['ip'] = get_client_ip();
        if (config('app..mongodb.hostname') != '') {
            Db::connect('mongodb')->name('operatelog')->insert($data);
        }
    }
}
function get_client_ip()
{
    $ip = 'unknown';
    if (isset($_SERVER)) {
        if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
        } elseif (isset($_SERVER['HTTP_CLIENT_ip'])) {
            $ip = $_SERVER['HTTP_CLIENT_ip'];
        } else {
            $ip = $_SERVER['REMOTE_ADDR'];
        }
    } else {
        if (getenv('HTTP_X_FORWARDED_FOR')) {
            $ip = getenv('HTTP_X_FORWARDED_FOR');
        } elseif (getenv('HTTP_CLIENT_ip')) {
            $ip = getenv('HTTP_CLIENT_ip');
        } else {
            $ip = getenv('REMOTE_ADDR');
        }
    }
    if (trim($ip)=='::1') {
        $ip='127.0.0.1';
    }
    return $ip;
}
function checkphone($str)
{
    $pattern = '/^1[356789]{1}\d{9}$/';
    if (preg_match($pattern, $str)) {
        return true;
    } else {
        return false;
    }
}
function checktel($str)
{
    $isTel='/^([0-9]{3,4}-)?[0-9]{7,8}$/';
    if (preg_match($isTel, $str)) {
        return true;
    } else {
        return false;
    }
}
function make_salt($length = 7)
{
    $chars = array('a','b','c','d','e','f','g','h',
    'i','j','k','l','m','n','o','p','q','r','s',
    't','u','v','w','x','y','z','A','B','C','D',
    'E','F','G','H','I','J','K','L','M','N','O',
    'P','Q','R','S','T','U','V','W','X','Y','Z',
    '0','1','2','3','4','5','6','7','8','9','!',
    '@','#','$','%','^','&','*','(',')','-','_',
    '[',']','{','}','<','>','~','`','+','=',',',
    '.',';',':','/','?','|');
    $keys = array_rand($chars, $length);
    $user_salt = '';
    for ($i = 0; $i < $length; $i++) {
        $user_salt .= $chars[$keys[$i]];
    }
    return $user_salt;
}
function create_uuid($prefix = 'SQ')
{    //可以指定前缀
    $str = md5(uniqid(mt_rand(), true));
    $uuid  = substr($str, 0, 8) . '-';
    $uuid .= substr($str, 8, 4) . '-';
    $uuid .= substr($str, 12, 4) . '-';
    $uuid .= substr($str, 16, 4) . '-';
    $uuid .= substr($str, 20, 12);
    return $prefix . $uuid;
}
/**
 * 唯一ID生成
 * @param string $prefix
 * @return void
 * @author QianLong <87498106@qq.com>
 * @date 2021-03-29 16:32:00
 * @editAuthor QianLong <87498106@qq.com>
 * @editDescription 
 * @editDate 2021-03-29 16:32:00
 */
function createId($prefix = ''){
    return (new \Qianlong\SnowFlake\SnowFlake)->createId($prefix);
}
function checkemail($str)
{
    $pattern = '/^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/';
    if (preg_match($pattern, $str)) {
        return true;
    } else {
        return false;
    }
}
/**
 * 系统加密方法
 * @param string $data 要加密的字符串
 * @param string $key 加密密钥
 * @param int $expire 过期时间 单位 秒
 * @return string
 */
function think_encrypt($data, $key = '', $expire = 0)
{
    $key  = md5(empty($key) ? config('app..SYS_STATIC.pass_salt') : $key);
    $data = base64_encode($data);
    $x    = 0;
    $len  = strlen($data);
    $l    = strlen($key);
    $char = '';

    for ($i = 0; $i < $len; $i++) {
        if ($x == $l) $x = 0;
        $char .= substr($key, $x, 1);
        $x++;
    }

    $str = sprintf('%010d', $expire ? $expire + time() : 0);

    for ($i = 0; $i < $len; $i++) {
        $str .= chr(ord(substr($data, $i, 1)) + (ord(substr($char, $i, 1))) % 256);
    }

    $str = str_replace(array('+', '/', '='), array('-', '_', ''), base64_encode($str));
    return strtoupper(md5($str)) . $str;
}

/**
 * 系统解密方法
 * @param  string $data 要解密的字符串 （必须是think_encrypt方法加密的字符串）
 * @param  string $key 加密密钥
 * @return string
 */
function think_decrypt($data, $key = '')
{
    $key  = md5(empty($key) ? config('app..SYS_STATIC.pass_salt') : $key);
    $data = substr($data, 32);
    $data = str_replace(array('-', '_'), array('+', '/'), $data);
    $mod4 = strlen($data) % 4;
    if ($mod4) {
        $data .= substr('====', $mod4);
    }
    $data   = base64_decode($data);
    $expire = substr($data, 0, 10);
    $data   = substr($data, 10);

    if ($expire > 0 && $expire < time()) {
        return '';
    }
    $x    = 0;
    $len  = strlen($data);
    $l    = strlen($key);
    $char = $str = '';

    for ($i = 0; $i < $len; $i++) {
        if ($x == $l) $x = 0;
        $char .= substr($key, $x, 1);
        $x++;
    }

    for ($i = 0; $i < $len; $i++) {
        if (ord(substr($data, $i, 1)) < ord(substr($char, $i, 1))) {
            $str .= chr((ord(substr($data, $i, 1)) + 256) - ord(substr($char, $i, 1)));
        } else {
            $str .= chr(ord(substr($data, $i, 1)) - ord(substr($char, $i, 1)));
        }
    }
    return base64_decode($str);
}
// function new_oss()
// {
//     //获取配置项，并赋值给对象$config
//     $config=config('app..aliyun_oss');
//     //实例化OSS
//     $oss=new \OSS\OssClient($config['KeyId'], $config['KeySecret'], $config['Endpoint']);
//     return $oss;
// }
// function uploadFile($object, $Path)
// {
//     //try 要执行的代码,如果代码执行过程中某一条语句发生异常,则程序直接跳转到CATCH块中,由$e收集错误信息和显示
//     try {
//         $ossClient = new_oss();
//         if (is_null($ossClient)) {
//             exit(1);
//         }
//         //uploadFile的上传方法
//         $oss_data = $ossClient->uploadFile(config('app..aliyun_oss')['Bucket'], $object, $Path);
//         return $oss_data;
//     } catch (OssException $e) {
//         return $e->getMessage();
//     }
//     //否则，完成上传操作
//     return true;
// }
// function getOssSecureUrl($object, $timeout = 60)
// {
//     $ossClient = new_oss();
//     if (is_null($ossClient)) {
//         exit(1);
//     }
//     try {
//         $signedUrl = $ossClient->signUrl(config('app..aliyun_oss')['Bucket'], $object, $timeout);
//     } catch (OssException $e) {
//         printf(__FUNCTION__ . ": FAILED\n");
//         printf($e->getMessage() . "\n");
//         return;
//     }
//     if (strpos($signedUrl, 'http://') === 0) {
//         $table_change = array('http://'=>'https://');
//         $signedUrl = strtr($signedUrl, $table_change);
//     }
//     $signedUrl = str_replace('-internal','',$signedUrl);
//     return $signedUrl;
// }
// function getOssUrl($object)
// {
//     $url = config('app..aliyun_oss')['OSS_WEB_SITE'];
//     return $url.$object;
// }
// function deleteOssFile($object)
// {
//     $ossClient = new_oss();
//     if (is_null($ossClient)) {
//         exit(1);
//     }
//     try {
//         $signedUrl = $ossClient->deleteObject(config('app..aliyun_oss')['Bucket'], $object);
//         return $signedUrl;
//     } catch (OssException $e) {
//         return $e->getMessage();
//     }
// }
function export2excel($data, $file='', $fields='', $field_titles='', $sheet_name='OrderLists')
{
    $file= (empty($file)) ? 'SC'.date('YmdHis').random_int(100000, 999999) : $file;
    //处理数据
    $field_titles=empty($field_titles)?array():explode(',', $field_titles);
    $fields=explode(',', $fields);
    $rst=array();
    $rsttitle=array();
    $title_y_n=(count($fields)==count($field_titles))?true:false;
    foreach ($fields as $k=>$v) {
        if (in_array($v, $fields)) {
            $rst[]=$v;
            //一一对应则取指定标题,否则取字段名
            $rsttitle[]=$title_y_n?$field_titles[$k]:$v;
        }
    }
    $fields=$rst;
    $field_titles=$rsttitle;
    //import('Org.Util.PHPExcel');
    error_reporting(E_ALL);
    date_default_timezone_set('Asia/chongqing');
    $objPHPExcel = new \PHPExcel();
    //import('Org.Util.PHPExcel.Reader.Excel5');
    /*设置excel的属性*/
    $objPHPExcel->getProperties()->setCreator('www.iznsq.cn')//创建人
      ->setLastModifiedBy('www.iznsq.cn')//最后修改人
      ->setKeywords('excel')//关键字
      ->setCategory('result file');//种类

      //第一行数据
    $objPHPExcel->setActiveSheetIndex(0);
    $active = $objPHPExcel->getActiveSheet();
    foreach ($field_titles as $i=>$name) {
        $ck = num2alpha($i++) . '1';
        $active->setCellValue($ck, $name);
    }
    //填充数据
    foreach ($data as $k => $v) {
        $k=$k+1;
        $num=$k+1;//数据从第二行开始录入
        $objPHPExcel->setActiveSheetIndex(0);
        foreach ($fields as $i=>$name) {
            $ck = num2alpha($i++) . $num;
            $active->setCellValue($ck, $v[$name]);
        }
    }
    $objPHPExcel->getActiveSheet()->setTitle($sheet_name);
    $objPHPExcel->setActiveSheetIndex(0);
    header('Content-Type: application/vnd.ms-excel');
    header('Content-Disposition: attachment;filename="'.$file.'.xls"');
    header('Cache-Control: max-age=0');
    $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
    $objWriter->save('php://output');
    exit;
}